<template>
    <div>
        <table-search v-if="isSearch" @search="search(1)" @reset="reset()">
            <template slot="form">
                <form-item label="">
                    <a-input v-model.trim="form.userName" placeholder="姓名" />
                </form-item>
                <!-- <form-item label="">
                    <a-input v-model.trim="form.tel" placeholder="手机号" />
                </form-item> -->
                <form-item label="">
                    <a-select v-model="form.status" style="width: 120px" allowClear placeholder="请选择状态">
                        <a-select-option :value="0">停用</a-select-option>
                        <a-select-option :value="1">正常</a-select-option>
                    </a-select>
                </form-item>
            </template>
            <template slot="extra">
                <a-button
                    class="filter-item"
                    :disabled="hasPerm(['sys:user:add'])"
                    type="primary"
                    icon="plus"
                    @click="addInfo()"
                    >新增用户</a-button
                >
                <a-button
                    class="filter-item btn_space"
                    type="danger"
                    @click="remove()"
                    :disabled="!selectionBox.length || hasPerm(['sys:user:remove'])"
                    icon="delete"
                    >删除</a-button
                >
            </template>
        </table-search>
        <table-list
            :loading="loading"
            :columns="columns"
            :data="list"
            rowKey="userId"
            :pagination="pagination"
            :selection="isSearch ? selection : null"
        >
            <template slot="roleName" slot-scope="{ text }">
                <span>{{ text.role }}</span>
            </template>
            <template slot="switch" slot-scope="{ text }">
                <a-switch
                    checked-children="正常"
                    un-checked-children="禁用"
                    :key="text.tenantId"
                    :disabled="
                        hasPerm(['sys:user:update']) || text.userId == account.userId || text.userType == 'super_admin'
                    "
                    :default-checked="text.status == 1 ? true : false"
                    @change="onSwitchStatus(text)"
                />
            </template>
            <template slot="action" slot-scope="{ text, index }">
                <a-button
                    size="small"
                    type="default"
                    :disabled="hasPerm(['sys:user:reset']) || text.userId == account.userId"
                    @click="resetPWD(text)"
                    >重置密码</a-button
                >
                <a-button
                    size="small"
                    type="primary"
                    class="btn_space"
                    :disabled="hasPerm(['sys:user:update']) || text.userType == 'super_admin'"
                    @click="addInfo(text, index)"
                    >编辑</a-button
                >
                <a-button
                    type="danger"
                    size="small"
                    class="btn_space"
                    :disabled="
                        hasPerm(['sys:user:remove']) || text.userId == account.userId || text.userType == 'super_admin'
                    "
                    @click="remove(text)"
                >
                    删除
                </a-button>
            </template>
        </table-list>

        <template v-if="isShowInfo">
            <user-info :info="itemInfo" @cancel="isShowInfo = false" @submit="submit" />
        </template>

        <template v-if="isShowPwd">
            <user-pwd :info="itemInfo" @cancel="isShowPwd = false" @submit="submit" />
        </template>
    </div>
</template>
<script>
import table from '@/mixins/table';
import { columns } from './columns';
import UserInfo from '../UserInfo';
import UserPwd from '../UserPwd';
import { mapState } from 'vuex';
import { remoteList, deleteInfo, updateInfo } from '@/api/system/user';
import { resetPassword } from '@/api/user';

export default {
    name: 'UserList',
    mixins: [table],
    props: {
        params: {
            //列表接口筛选的参数
            type: Object,
            default: () => {}
        },
        isSearch: {
            type: Boolean,
            default: false
        }
    },
    components: {
        UserInfo,
        UserPwd
    },
    computed: {
        ...mapState({
            account: state => state.user.accountInfo
        })
    },
    data() {
        let originForm = {
            userName: null,
            status: undefined
        };
        return {
            originForm,
            columns,
            form: {
                ...originForm
            },
            itemInfo: null,
            isShowInfo: false,
            list: [],
            isShowPwd: false
        };
    },
    watch: {
        params: {
            handler(now, pre) {
                if (JSON.stringify(now) == JSON.stringify(pre)) return false;
                this.form = { ...this.form, ...now };
                this.search(1);
            },
            deep: true
        }
    },
    created() {
        this.search(1);
    },
    methods: {
        async search(page) {
            try {
                this.loading = true;
                if (page) {
                    this.form.page = page;
                }
                this.list = [];
                let res = await remoteList(this.form);
                let { list, total } = res.data;
                this.list = list;
                this.total = total;
            } finally {
                this.loading = false;
            }
        },
        //显示添加用户
        addInfo(item = {}) {
            this.isShowInfo = true;
            this.itemInfo = item;
        },
        //是否开启
        async onSwitchStatus(item) {
            try {
                let { status } = item;
                item.status = status == 1 ? 0 : 1;
                this.loading = true;
                await updateInfo(item);
                this.$message.success('操作成功!');
            } catch (err) {
                let { status } = item;
                item.status = status ? 0 : 1;
            } finally {
                this.loading = false;
            }
        },
        //更新数据
        submit() {
            this.isShowInfo = false;
            this.isShowPwd = false;
            this.search(1);
        },
        //删除
        remove(item = '') {
            this.$confirm({
                title: '提示',
                content: '确定要删除用户信息？',
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        let ids = [];
                        if (item) {
                            ids = [item.userId];
                        } else {
                            let selectionBox = this.selectionBox;
                            console.log(selectionBox);
                            selectionBox.map(async item => {
                                ids.push(item.userId);
                            });
                        }
                        await deleteInfo({ ids });
                        this.$message.success('删除成功!');
                        this.search(1);
                    } catch (err) {}
                },
                onCancel() {}
            });
        },
        //重置密码
        resetPWD(item) {
            // this.isShowPwd = true;
            // this.itemInfo = item;
            let that = this;
            this.$confirm({
                title: '提示',
                content: `确定要将账号 ${item.userName} 的密码重置为:123456吗？`,
                okText: '确定',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        let data = {
                            tenantCode: item.tenantCode,
                            userName: item.userName,
                            userType: item.userType
                        };
                        let res = await resetPassword(data);
                        that.$message.success(`已将账号 ${item.userName} 的密码重置为:123456`);
                    } catch (err) {}
                },
                onCancel() {}
            });
        }
    }
};
</script>
